Ti.include('../class/const.js');
//Ti.include('../class/user.js');
Ti.include('../class/network.js');
Ti.include('../class/db.js');
Ti.include('../viewHelper/ideaListViews.js');
Ti.include('../viewHelper/infoPopup.js');

var default_cookie_value = "";
var cookie_string = Ti.App.Properties.getString("cookie_sessio",default_cookie_value);
Ti.App.Properties.setString("cookie_sessio",cookie_string);
Ti.API.info("contenido de cookie:" + cookie_string);

var win = Ti.UI.currentWindow;
var views = ideaListViews.getViews();
var currentTab = 1;
//win.add(views.nav);
Ti.App.ideaNavigationGroup = views.nav;
win.add(views.nav);

if (parseFloat(Titanium.Platform.version) < 4.2){	
	views.nav.window.title = L("ideas en curs");
	views.nav.window.rightNavButton = Titanium.UI.createButton({
		systemButton:Titanium.UI.iPhone.SystemButton.INFO_LIGHT
	});

}else{
	views.nav.window.titleControl = views.tabbedBar;
	
}
views.activityIndicatorView.add(views.activityIndicator);
win.add(views.activityIndicatorView);
views.nav.window.add(views.waitingTorrentTableView);
views.nav.window.add(views.inCourseTorrentTableView);
views.nav.window.add(views.doneTorrentTableView);

// event listeners
Ti.App.addEventListener('openIdeaWindowById', function (item){
	Ti.API.info("openIdeaWindowById idIdea:"+item.idIdea);
	if (item.idIdea != null){
		var ideaWindow = ideaListViews.getIdeaWindowByData(item.idIdea); 
		Ti.App.ideaNavigationGroup.open(ideaWindow,{animated:true});
	}
});

views.waitingTorrentTableView.addEventListener('click',  function(elem){
	Ti.App.fireEvent('openIdeaWindowById',{idIdea:elem.rowData.idIdea});
});

views.inCourseTorrentTableView.addEventListener('click', function(elem){
	Ti.App.fireEvent('openIdeaWindowById',{idIdea:elem.rowData.idIdea});
});
views.doneTorrentTableView.addEventListener('click', function(elem){
	Ti.App.fireEvent('openIdeaWindowById',{idIdea:elem.rowData.idIdea});
});

Ti.App.addEventListener('openLastTab', function (item){
	views.tabbedBar.index =currentTab;
});

views.tabbedBar.addEventListener('click', function(e){
	Ti.API.info("barraBotons.click: e.index:"+e.index);
	switch (e.index){
	case 0: // en espera
		views.waitingTorrentTableView.show();
		views.inCourseTorrentTableView.hide();
		views.doneTorrentTableView.hide();
		break;
	
	case 1: // en curs
		views.waitingTorrentTableView.hide();
		views.inCourseTorrentTableView.show();
		views.doneTorrentTableView.hide();
		break;
	
	case 2: // acabades
		views.waitingTorrentTableView.hide();
		views.inCourseTorrentTableView.hide();
		views.doneTorrentTableView.show();
		break;
	}
	currentTab = e.index;
});

Ti.App.addEventListener('updateTabBadgeFromDb', function(response){
	Ti.API.info("updateTabBadgeFromDb start");
	var newIdeas = Db.countNewOrUpdatedIdeas();
	var newSolucions = Db.countNewOrUpdatedSolucions();
	var totalChanges = newIdeas + newSolucions;
	Ti.App.fireEvent('setTabBadge',{number:newIdeas + "/" +newSolucions });
});

Ti.App.addEventListener('fillTorrentTablesFromDatabase', function(){
	Ti.API.info("fillTorrentTablesFromDatabase start");
	Db.clearIdeaStateForOldIdeas();
	var currentIdea = null;
	var currentTable = null;
	var tablesToFill = [{ rows: [], visible: currentTab==0, ideas: Db.retrieveIdeasByStatus(IDEA_STATUS_WAITING), tableView: views.waitingTorrentTableView  },
	                    { rows: [], visible: currentTab==1 , ideas: Db.retrieveIdeasByStatus(IDEA_STATUS_INCOURSE), tableView: views.inCourseTorrentTableView },
	                    { rows: [], visible: currentTab==2, ideas: Db.retrieveIdeasByStatus(IDEA_STATUS_DONE), tableView: views.doneTorrentTableView }];
	for (i=0;i< tablesToFill.length;i++){
		currentTable = tablesToFill[i];
		if(currentTable.ideas== false){
			currentTable.rows.push(ideaListViews.makeNoTorrentsRow());
		}else{
			for(j=0;j<currentTable.ideas.length;j++){
				currentIdea = currentTable.ideas[j];
				currentTable.rows.push(ideaListViews.makeRow(currentIdea));
			}
		}
		currentTable.tableView.setData(currentTable.rows);
		if(currentTable.visible){
			if (views.tabbedBar.index != i){
				views.tabbedBar.fireEvent("click",{index:i});
				views.tabbedBar.index = i;
			}
		}
	}
});


Ti.App.addEventListener('torrentDownloadOk', function(response){
	
	var currentIdea = null;
	var currentSection = null;
	var responseJson = JSON.parse(response.text);
	for(var statusId in responseJson){
		
		if (!isNaN(statusId) /*&& (statusId == IDEA_STATUS_INCOURSE || statusId == IDEA_STATUS_DONE || statusId == IDEA_STATUS_WAITING)*/){
			currentSection = responseJson[statusId];
			for(var ideaId in currentSection){
				if (!isNaN(ideaId)){
					Ti.API.info("updateDbFromJson idea:" + ideaId);
					currentIdea = currentSection[ideaId];
		    		Db.insertOrUpdateIdea(currentIdea);
		    		if (currentIdea.s != null && currentIdea.s !=""){
		    			for(var solucioId in currentIdea.s){
		    				if (!isNaN(solucioId)){
		    					Ti.API.info("updateDbFromJson solucio:" + solucioId);
		    					Db.insertOrUpdateSolucio(currentIdea.s[solucioId]);
		    				}
		    			}
		    		}
				}
		    }
		}
	}
	views.activityIndicatorView.hide();
	Ti.App.fireEvent('fillTorrentTablesFromDatabase');
});

Ti.App.addEventListener('torrentDownloadKo', function(statusObj){
	views.activityIndicatorView.hide();
	Ti.App.fireEvent('fillTorrentTablesFromDatabase');
	if(statusObj.status != 'no network'){
		var alertDialog = Titanium.UI.createAlertDialog({
			title: L('WARNING'),
			message: L('Your device is not online.'),
			buttonNames: ['OK']
        });
		alertDialog.show();
	}
});

Ti.App.addEventListener('dbFinishedInit', function(){
	views.activityIndicatorView.show();
	network.getTorrents();
});

//Db.resetDb();
Db.init();
infoPopup.showFirstTimeMessage();

views.nav.window.rightNavButton.addEventListener('click',function(){
	infoPopup.show();
});


Ti.App.addEventListener('resume', function(){
	Ti.API.info("app event open sent to ideaListWindow");
	Db.init();
});